<template>
  <div class="overviewContent" id="overviewContent">
    <div class="overviewContentHeader">
      <!-- 吸顶 -->

      <div class="flexTop">
        <div class="header">
          <div class="header-left">
            <h1>运行监测</h1>
          </div>
          <div class="header-right">
            <a-input-group compact>
              <a-select
                v-model:value="form.type"
                style="width: 40%"
                @change="changeFilterType"
              >
                <a-select-option
                  v-for="item in FILTER_TYPE"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.type }}
                </a-select-option>
              </a-select>
              <a-select
                v-model:value="form.value"
                style="width: 60%"
                allow-clear
                v-if="form.type !== 4 && form.type !== 5"
                show-search
                optionFilterProp="label"
              >
                <a-select-option
                  v-for="item in selectList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <a-select
                v-model:value="form.value"
                style="width: 60%"
                allow-clear
                v-else-if="form.type === 5"
              >
                <a-select-option
                  v-for="item in STATION_STATUS"
                  :key="item.value"
                  :value="item.value"
                  :label="item.type"
                >
                  {{ item.type }}
                </a-select-option>
              </a-select>
              <a-input
                v-model:value="form.value"
                class="formInput"
                placeholder="请输入"
                v-else
                style="width: 60%"
                allow-clear
              />
            </a-input-group>
            <a-button type="primary" @click="handleSearch">查询</a-button>
          </div>
        </div>

        <!-- <div class="header">
        <div class="header-left">
          <h1>运行监测</h1>
        </div>
        <div class="header-right">
          <a-input-group compact>
            <a-select
              v-model:value="form.type"
              style="width: 40%"
              @change="changeFilterType"
            >
              <a-select-option
                v-for="item in FILTER_TYPE"
                :key="item.value"
                :value="item.value"
              >
                {{ item.type }}
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="form.value"
              style="width: 60%"
              allow-clear
              v-if="form.type !== 4 && form.type !== 5"
              show-search
              optionFilterProp="label"
            >
              <a-select-option
                v-for="item in selectList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="form.value"
              style="width: 60%"
              allow-clear
              v-else-if="form.type === 5"
            >
              <a-select-option
                v-for="item in STATION_STATUS"
                :key="item.value"
                :value="item.value"
                :label="item.type"
              >
                {{ item.type }}
              </a-select-option>
            </a-select>
            <a-input
              v-model:value="form.value"
              class="formInput"
              placeholder="请输入"
              v-else
              style="width: 60%"
              allow-clear
            />
          </a-input-group>
          <a-button type="primary" @click="handleSearch">查询</a-button>
        </div>
      </div> -->
        <div class="summary-cards">
          <div class="summary-card">
            <i class="fas fa-charging-station"></i>
            <div class="content">
              <div class="value">
                {{ stationOverview.total }}<span>座</span>
              </div>
              <div class="label">电站数量</div>
            </div>
          </div>
          <div class="summary-card">
            <i class="fas fa-bolt"></i>
            <div class="content">
              <div class="value">
                {{ stationOverview.capacity }}<span>MWh</span>
              </div>
              <div class="label">项目总容量</div>
            </div>
          </div>
          <div class="summary-card">
            <i class="fas fa-exchange-alt"></i>
            <div class="content">
              <div class="value">
                {{ stationOverview.totalCharge }}<span>万kwh</span>
              </div>
              <div class="label">累计充电</div>
            </div>
          </div>
          <div class="summary-card">
            <i class="fas fa-totalexchange-alt"></i>
            <div class="content">
              <div class="value">
                {{ stationOverview.totalDischarge }}<span>万kwh</span>
              </div>
              <div class="label">累计放电量</div>
            </div>
          </div>
          <div class="summary-card">
            <i class="fas fa-wallet"></i>
            <div class="content">
              <div class="value">
                {{ stationOverview.todayIncome }}<span>元</span>
              </div>
              <div class="label">今日收益</div>
            </div>
          </div>
          <div class="summary-card">
            <i class="fas fa-totalwallet"></i>
            <div class="content">
              <div class="value">
                {{ stationOverview.totalIncome }}<span>万元</span>
              </div>
              <div class="label">累计收益</div>
            </div>
          </div>
          <!-- <div class="summary-card">
          <i class="fas fa-leaf"></i>
          <div class="content">
            <div class="value">343.26<span>吨</span></div>
            <div class="label">累计减少碳排放</div>
          </div>
        </div> -->
        </div>
      </div>
      <div class="cardList">
        <a-spin :spinning="chartLoading">
          <div v-if="stationInfList.length > 0">
            <StationCard
              :stationInfList="stationInfList"
              @getStationOverview="getStationOverview"
              @loadMore="loadMoreData"
              :hasMore="hasMoreData"
              :loading="loadingMore"
            />
          </div>
          <div
            style="
              min-height: calc(100vh - 270px);
              display: flex;
              justify-content: center;
              align-items: center;
            "
            v-else
          >
            <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
          </div>
        </a-spin>
      </div>
    </div>
  </div>
</template>
<script setup>

import { Empty } from 'ant-design-vue'
import { FILTER_TYPE, STATION_STATUS } from "@/constants/monitoringCenter"
import { INVESTORS_LIST } from "@/constants/stationConfig"
import StationCard from "./conpoments/stationCard.vue"
import moment from "moment"

const $api = inject("$api")
const form = ref({
  type: 1,
  value: "",
  size: 9999,
  page: 1,
})

//请求所有电站
const selectList = ref([])
const getStationList = async () => {
  const res = await $api.companyStationtList({})
  if (res && res.code === 0) {
    selectList.value = res.data.map((item) => ({
      name: item.stationName,
      id: item.stationId,
    }))
  }
}
//获取所有企业
const getCompanyList = async () => {
  const res = await $api.companyList({})
  if (res && res.code === 0) {
    selectList.value = res.data.map((item) => ({
      name: item.projectName,
      id: item.id,
    }))
  }
}
//获取所有项目分组
const getGroupList = async () => {
  const res = await $api.projectGroupList({ groupName: "" })
  if (res && res.code === 0) {
    selectList.value = res.data.map((item) => ({
      name: item.name,
      id: item.id,
    }))
  }
}
//获取当前有项目的省份
const getCompanyProvStats = async () => {
  let res = await $api.companyProvStats()
  selectList.value = res.data.map((item) => ({
    name: item.provName,
    id: item.provId,
  }))
  console.log(selectList.value)
}
//获取所有运行负责人

const searchUser = async (value) => {
  const res = await $api.userListData({
    username: value,
  })
  if (res.code === 0) {
    selectList.value = res.data.map((item) => ({
      name: item.username,
      id: item.id,
    }))
    //userList.value = res.data
  }
}
//搜索类型变更
const changeFilterType = (e) => {
  form.value.value = ""
  switch (e) {
    case 1:
      getStationList()
      return
    /*  case 2:
      getCompanyList()
      return */
    case 3:
      getGroupList()
      return
    /* case 4:
      return */
    case 5:
      selectList.value = [
        { name: "在线", id: 1 },
        { name: "离线", id: 0 },
      ]
      return
    case 6:
      getCompanyProvStats()
      return
    case 7:
      selectList.value = INVESTORS_LIST.map((item) => {
        item.name = item.label
        item.id = item.value
        return item
      })
      return
    /* case 8:
      searchUser()
      return */
    case 9:
      selectList.value = [
        { name: "是", id: 1 },
        { name: "否", id: 0 },
      ]
      return
    case 10:
      selectList.value = [
        { name: "是", id: 1 },
        { name: "否", id: 0 },
      ]
      return
    case 11:
      selectList.value = [
        { name: "是", id: 1 },
        { name: "否", id: 0 },
      ]
      return
    default:
      getStationList()
      return
  }
}

// 处理搜索按钮点击
const handleSearch = () => {
  form.value.page = 1
  stationInfList.value = []
  // 重置状态数据分页参数
  statusParams.value = {
    page: 1,
    size: 12,
    loadedPages: new Set(),
  }
  ChargingInfList.value = []
  statusHasMoreData.value = true
  getStationOverview()
}

//获取电站总览数据
let stationOverview = ref({})
const chartLoading = ref(false)
let stationInfList = ref([])
const hasMoreData = ref(true)
const loadingMore = ref(false)

// 状态数据分页参数
const statusParams = ref({
  page: 1,
  size: 12,
  loadedPages: new Set(), // 记录已加载的页码，避免重复请求
})

const getStationOverview = async (isLoadMore = false) => {
  // 过滤掉空值参数
  const params = Object.fromEntries(
    Object.entries(form.value).filter(
      ([_, value]) =>
        value !== "" &&
        value !== null &&
        value !== undefined &&
        !(Array.isArray(value) && value.length === 0)
    )
  )
  if (!isLoadMore) {
    chartLoading.value = true
  } else {
    loadingMore.value = true
  }

  /*  const res = await $api.stationOverviewData(params)
  const res2 = await $api.statisticsData(params) */
  //const res3 = await $api.statusData(params)
  Promise.all([
    $api.stationOverviewData(params),
    $api.statisticsData(params),
  ]).then(([res, res2]) => {
    if (res && res.code === 0) {
      const { stationContents, ...other } = res.data
      stationOverview.value = other
      const processedData = stationContents.map((item) => {
        const matchingStation = res2.data.stationContents.find(
          (s) => s.stationId === item.stationId
        )
        if (matchingStation) {
          item = { ...item, ...matchingStation }
        }
        item.companyCreateTime = moment(item.companyCreateTime).format(
          "YYYY-MM-DD"
        )
        item.totalChargeProgress =
          (
            item.stationTotalCharge /
            (item.stationTotalCharge + item.stationTotalDischarge)
          ).toFixed(2) * 100
        item.monthChargeProgress =
          (item.monthCharge / (item.monthCharge + item.monthDischarge)).toFixed(
            2
          ) * 100
        if (item.status === 2) {
          item.statusClassName = "building"
        } else if (item.status === 4) {
          item.statusClassName = "stop"
        } else if (item.status === 1) {
          item.statusClassName = "toBuilding"
        } else {
          item.statusClassName = ""
        }

        if (item.stationShortName) {
          item.companyShortNmaeStyle =
            [...item.stationShortName.replace(/\s/g, "")].length >= 4 ? 17 : 16
        }
        return item
      })
      if (isLoadMore) {
        stationInfList.value = [...stationInfList.value, ...processedData]
      } else {
        stationInfList.value = processedData
      }

      // 判断是否还有更多数据
      hasMoreData.value = processedData.length === form.value.size
      //stationInfList.value = processedData
    }
    if (res2 && res2.code === 0) {
      stationOverview.value = { ...stationOverview.value, ...res2.data }
    }

    chartLoading.value = false
    loadingMore.value = false
    getStationChargingStatus(params)
  })
}
let ChargingInfList = ref([])
const statusHasMoreData = ref(true) // 状态数据是否还有更多
const statusLoadingMore = ref(false) // 状态数据是否正在加载更多

const getStationChargingStatus = async (params, isLoadMore = false) => {
  // 如果是加载更多但已经没有更多数据，则直接返回
  if (isLoadMore && !statusHasMoreData.value) return

  // 如果当前页已经加载过，则跳过
  if (statusParams.value.loadedPages.has(statusParams.value.page)) return

  if (isLoadMore) {
    statusLoadingMore.value = true
  }

  // 构建请求参数，合并基本参数和分页参数
  const requestParams = {
    ...params,
    current: statusParams.value.page,
    size: statusParams.value.size,
  }

  const res3 = await $api.statusData(requestParams)
  if (res3 && res3.code === 0) {
    if (res3.data && res3.data.stationContents) {
      // 记录当前页已加载
      statusParams.value.loadedPages.add(statusParams.value.page)

      // 处理返回的数据
      const processedData = res3.data.stationContents.map((item) => {
        if (
          item.freeChargeLinkNumber === 0 &&
          item.chargeLinkNumber === 0 &&
          item.dischargeLinkNumber !== 0
        ) {
          //放电
          item.CDStatus = "放电"
        } else if (
          item.freeChargeLinkNumber === 0 &&
          item.dischargeLinkNumber === 0 &&
          item.chargeLinkNumber !== 0
        ) {
          //充电
          item.CDStatus = "充电"
        } else if (
          item.freeChargeLinkNumber !== 0 &&
          item.dischargeLinkNumber === 0 &&
          item.chargeLinkNumber === 0
        ) {
          //空闲
          item.CDStatus = "待机"
        } else if (
          item.freeChargeLinkNumber != 0 &&
          item.chargeLinkNumber != 0 &&
          item.dischargeLinkNumber === 0
        ) {
          //充电且有空闲电池堆
          item.CDStatus = `充${item.chargeLinkNumber}待${item.freeChargeLinkNumber}`
        } else if (
          item.freeChargeLinkNumber != 0 &&
          item.dischargeLinkNumber != 0 &&
          item.chargeLinkNumber === 0
        ) {
          //放电且有空闲电池堆
          item.CDStatus = `放${item.dischargeLinkNumber}待${item.freeChargeLinkNumber}`
        } else if (
          item.freeChargeLinkNumber !== 0 &&
          item.dischargeLinkNumber !== 0 &&
          item.chargeLinkNumber !== 0
        ) {
          //有充电有放电且有空闲
          item.CDStatus = `充${item.chargeLinkNumber}放${item.dischargeLinkNumber}待${item.freeChargeLinkNumber}`
        } else if (
          item.freeChargeLinkNumber === 0 &&
          item.dischargeLinkNumber !== 0 &&
          item.chargeLinkNumber !== 0
        ) {
          //有充有放
          item.CDStatus = `充${item.chargeLinkNumber}放${item.dischargeLinkNumber}`
        } else {
          item.CDStatus = null
        }

        return item
      })

      // 添加到现有数据中
      ChargingInfList.value = [...ChargingInfList.value, ...processedData]

      // 更新电站列表中的状态信息
      stationInfList.value = stationInfList.value.map((station) => {
        const matchingStation = processedData.find(
          (s) => s.stationId === station.stationId
        )
        if (matchingStation) {
          return { ...station, ...matchingStation }
        }
        return station
      })
      // 判断是否还有更多数据
      statusHasMoreData.value = processedData.length === statusParams.value.size
    } else {
      statusHasMoreData.value = false
    }
  }

  statusLoadingMore.value = false
}

// 加载更多数据
const loadMoreData = () => {
  /* if (hasMoreData.value && !loadingMore.value) {
    form.value.page++
    getStationOverview(true)
  } */
}

// 加载更多状态数据
const loadMoreStatusData = () => {
  if (statusHasMoreData.value && !statusLoadingMore.value) {
    statusParams.value.page++
    getStationChargingStatus(true)
  }
}

// 监听滚动事件，检测是否需要加载更多状态数据
const handleScroll = () => {
  if (!statusHasMoreData.value || statusLoadingMore.value) return

  // 获取所有卡片元素
  const cards = document.querySelectorAll(".stationCard .card")
  if (cards.length === 0) return

  // 计算当前页的最后一个卡片索引
  const currentPageLastIndex =
    statusParams.value.page * statusParams.value.size - 1

  // 如果卡片数量不足，则不需要加载更多
  if (currentPageLastIndex >= cards.length) return

  // 获取第12个卡片（或当前页的最后一个卡片）
  const targetCard = cards[currentPageLastIndex]
  if (!targetCard) return

  // 获取卡片位置信息
  const rect = targetCard.getBoundingClientRect()

  // 当卡片顶部进入视口时，加载更多数据
  if (rect.top <= window.innerHeight) {
    loadMoreStatusData()
  }
}

let timer = null

onMounted(() => {
  getStationList()
  getStationOverview()

  // 添加滚动事件监听
  window.addEventListener("scroll", handleScroll, true)
  // 设置定时器，每15秒刷新一次数据
  /*  timer = setInterval(() => {
    getStationOverview()
  }, 15000) */
})

// 组件卸载时清除定时器和事件监听
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  // 移除滚动事件监听 - 添加第三个参数 true
  window.removeEventListener("scroll", handleScroll, true)
})
</script>
<style lang="less" scoped>
/* .overviewContent {
  background: #1a2e3f;
} */

.overviewContentHeader {
  position: relative;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  .header-left {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  .header-left h1 {
    font-size: 24px;
    margin: 0;
    font-weight: 700;
  }
  .header-right {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 400px;
  }
  .flexTop {
    width: calc(100% + 29px);
    position: sticky;
    top: 0px;
    left: 0;
    padding: 15px 17px 15px 12px;
    background: rgb(22, 38, 52);
    z-index: 99;
    margin-left: -12px;
    /*  .header {
      margin-bottom: 0;
    } */
  }
  .summary-cards {
    display: flex;
    justify-content: space-between;
    gap: 20px;
    margin-bottom: 20px;
    .summary-card {
      background: linear-gradient(
        to right,
        rgba(49, 114, 157, 0.4),
        rgba(255, 255, 255, 0.2)
      );
      padding: 20px;
      border-radius: 8px;
      flex: 1;
      display: flex;
      align-items: center;
      gap: 15px;
      i {
        font-size: 30px;
        width: 57px;
        height: 59px;
        background-color: #eee;
        border-radius: 50px;
        &.fa-charging-station {
          background: url("/src/assets/overview1.png") no-repeat center / 100%
            auto #eee;
        }
        &.fa-bolt {
          background: url("/src/assets/overview9.png") no-repeat center/ 100%
            auto #eee;
        }
        &.fa-exchange-alt {
          background: url("/src/assets/overview3.png") no-repeat center/ 100%
            auto #eee;
        }
        &.fa-totalexchange-alt {
          background: url("/src/assets/overview12.png") no-repeat center/ 100%
            auto #eee;
        }
        &.fa-wallet {
          background: url("/src/assets/overview5.png") no-repeat center/ 100%
            auto #eee;
        }
        &.fa-totalwallet {
          background: url("/src/assets/overview5.png") no-repeat center/ 100%
            auto #eee;
        }
        /*  &.fa-leaf {
          background: url("/src/assets/overview4.png") no-repeat center/ 100%
            auto #eee;
        } */
      }
      .content {
        display: flex;
        flex-direction: column;
      }
      .value {
        font-size: 20px;
        font-weight: 500;
        margin-bottom: 5px;
        span {
          font-size: 12px;
        }
      }
      .label {
        font-size: 14px;
        color: #94a3b8;
      }
    }
  }
  /* .cardList {
    height: calc(100vh - 300px);
    overflow-y: scroll;
  } */
  .station-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    .station-card {
      background-color: #334155;
      border-radius: 8px;
      padding: 15px;
      display: flex;
      flex-direction: column;
      position: relative;
      .station-name {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 5px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        span {
          font-weight: normal;
          font-size: 14px;
        }
        .tag {
          background-color: #475569;
          color: #e2e8f0;
          padding: 2px 5px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
      .company-info {
        font-size: 14px;
        color: #94a3b8;
        margin-bottom: 10px;
      }
      .capacity-info {
        font-size: 14px;
        margin-bottom: 5px;
      }
      .soc-info {
        font-size: 14px;
        margin-bottom: 10px;
      }
      .charge-discharge {
        display: flex;
        gap: 10px;
        margin-bottom: 10px;
        button {
          background-color: #4338ca;
          color: #e2e8f0;
          border: none;
          padding: 5px 10px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 12px;
        }
      }
      .status-icons {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        div {
          display: flex;
          flex-direction: column;
          align-items: center;
          font-size: 12px;
        }
        i {
          font-size: 20px;
          margin-bottom: 5px;
        }
        .offline {
          color: #94a3b8;
        }
        .charging {
          color: #4338ca;
        }
        .warning {
          color: #facc15;
        }
        .project {
          color: #34d399;
        }
      }
      .total-charge-discharge {
        font-size: 12px;
        margin-bottom: 5px;
      }
      .monthly-charge-discharge {
        font-size: 12px;
      }
      .corner-icon {
        position: absolute;
        top: 10px;
        right: 10px;
        font-size: 18px;
        color: #94a3b8;
      }
      .corner-icon-with-tag {
        position: absolute;
        top: 10px;
        right: 10px;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        i {
          font-size: 18px;
          color: #94a3b8;
        }
        .tag {
          background-color: #facc15;
          color: #1e293b;
          padding: 2px 5px;
          border-radius: 4px;
          font-size: 12px;
          &.green {
            background-color: #34d399;
          }
        }
      }
    }
  }
  .empty {
    display: flex;
  }
}
:deep(.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
  background-color: #132133 !important;
  border-color: #5a7181;
}
@media screen and (max-width: 1740px) {
  .summary-card {
    gap: 8px !important;
    padding: 20px 10px !important;
  }
  i {
    width: 45px !important;
    height: 47px !important;
  }
  .value {
    font-size: 16px !important;
  }
}
</style>
